package edu.hawaii.duedates;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

/**
 * HiStateLibrary class is for the Hawaii State Library system, the application handles the login 
 * and book information retrieval.  HiStateLibrary is part of the DueDates system.
 * 
 * @author John Ancheta, Daniel Arakaki, Mari-Lee Flestado
 * @version 1.0, November 10, 2008
 *
 */
public class HiStateLibrary {
  /**
   * Attempts to login to the Hawaii State Library System.
   * 
   * @param barcode The Hawaii library id barcode.
   * @param pin The password (last four digits of your phone number).
   * 
   * @return The WebConversation after logging in.
   * 
   * @throws Exception If errors occur while logging in.
   */
  private WebConversation loginToHawaiiStateLibrary(String barcode, String pin) throws Exception {
    try {
      String url = "http://www.librarieshawaii.org/";
      // Website has bogus JavaScript code.
      HttpUnitOptions.setExceptionsThrownOnScriptError(false);
      // create the conversation object which will maintain state for us
      WebConversation conversation = new WebConversation();
      WebRequest request = new GetMethodWebRequest(url);
      WebResponse response = conversation.getResponse(request);
      WebLink link = response.getLinkWith("My Account");
      link.click();
      response = conversation.getCurrentPage();
      WebForm form = response.getForms()[0];
      form.setParameter("sec1", barcode);
      form.setParameter("sec2", pin);
      form.submit();
      response = conversation.getCurrentPage();
      if (response.getText().contains("Login failed.")) {
        throw new Exception("Invalid account.");
      }
      return conversation;
    }
    catch (Exception e) {
      throw new Exception("Error while logging in to Hawaii State Library", e);
    }
  }
  
  /**
   * Gets info from the Hawaii State Library site.
   * 
   * @param hiStateId The barcode number from the library card.
   * @param hiStatePassword The password (normally the last four digits of your phone number).
   * @param bookList An array list of due dates and book titles.
   * 
   * @throws Exception If problems occur getting in the information.
   */
  public void getHawaiiStateInfo(String hiStateId, String hiStatePassword,
      List<BookInfoRecord> bookList) throws Exception {
    String dateFormat = "MM-dd-yyyy";
    DateFormat formattedDate = new SimpleDateFormat(dateFormat, Locale.US);
    try {
      WebConversation conversation = this.loginToHawaiiStateLibrary(hiStateId, hiStatePassword);
      WebResponse response = conversation.getCurrentPage();
      WebLink link = response.getLinkWith("Items Out");
      link.click();
      response = conversation.getCurrentPage();
      WebTable table = response.getTableStartingWith("Title");
      if (table != null) {
        int rowCount = table.getRowCount();
        for (int i = 1; i < rowCount; i++) {
          String title = table.getCellAsText(i, 0);
          String duedate = table.getCellAsText(i, 2);
          Date aDate = formattedDate.parse(duedate);
          bookList.add(new BookInfoRecord(aDate, title, "hsl"));
        }
      }
    }
    catch (Exception e) {
      throw new Exception("Error getting Hawaii State Library info.", e);
    }
  }
}
